package genstream.cp

import java.net.URL
import scaladuct.Starter
import genstream._
import javax.validation.constraints.NotNull

/**
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: 16.4.11
 * Time: 13:45
 * To change this template use File | Settings | File Templates.
 */

class ClasspathResource(resourcePath: String) extends InputResource {

  def this(cookie: ClasspathResourceStarterCookie) = this(cookie.resourcePath)

  def openIterator(context: StreamingContext) = {
    var urlList: List[URL] = Nil
    val resEnum = Thread.currentThread.getContextClassLoader.getResources(resourcePath)
    while (resEnum.hasMoreElements) {
      urlList ::= resEnum.nextElement
    }

    new URLInputStreamIterator(urlList)
  }

}

@serializable
@SerialVersionUID(1L)
class ClasspathResourceStarterCookie {
  @NotNull
  var resourcePath: String = null
}


@SerialVersionUID(1L)
class ClasspathResourceStarter extends Starter[ServiceFactory[ClasspathResource]] {

  def newInstance(): ServiceFactory[ClasspathResource] = phaseFile(new ClasspathResourceStarterCookie)

  def phaseFile(cookie: ClasspathResourceStarterCookie): ServiceFactory[ClasspathResource] = {
    new FunctionalServiceFactory(new ClasspathResource(cookie))
  }

  def destroy(instance: ServiceFactory[ClasspathResource]) = null

}